<?php
namespace frontend\controllers;

use common\models\Template;
use Yii;
use common\models\Login;
use common\models\User;
use common\models\Sms;
use common\models\Banner;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\components\Myhelpers;
use frontend\models\FindPasswordForm;

/**
 * Site controller
 */
class SiteController extends FController
{

    public $layout = 'main_simple';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'register'],
                'rules' => [
                    [
                        'actions' => ['register'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    //'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {

        return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {

        //查询登陆页广告图
        $banner=Banner::find()
                    ->select('id,name,img_url,link,width,height,target')
                    ->where(['pid'=>3,'enabled'=>1])
                    ->asArray()
                    ->orderBy('orderBy asc')
                    ->all();

        //修改页面标题
        Yii::$app->view->params['page']['page_title'] = '登录 - ' . $this->w_config['website_name'];

        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new Login();

        $error = 0;
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            //将本次登录时间写入user表
            $login_time = Yii::$app->db->createCommand()
                    ->update('user', ['last_login_time' =>date('Y-m-d H:i:s')],"id=".Yii::$app->user->id)
                    ->execute();
            if($login_time){
                $error = 2;
            }
            //return $this->goBack();
        }else{
            if(Yii::$app->request->post()){
                $error = 1;
            }
        }
       
       
                   

        return $this->render('login', [
            'model' => $model,
            'banner' => $banner,
            'error' =>$error
        ]);
    }
    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        //return $this->goHome();
        return $this->redirect(['site/login']);
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionRegister()
    {
        //验证手机号发送短信
        $phone = Myhelpers::RemoveXSS(Yii::$app->request->post('phonecode'));

        if($phone){
            $phone_uni = User::find()->where(['phone'=>$phone])->count();
            if(intval($phone_uni)){
                return 0;   //手机已存在
            }else{
                //生成验证码
                $verify_code = rand(1000,9999);

                //手机不在---调用接口发送短信---发送的时候保存到表里面
                //获取模板id
                $params = ['sms_reg' => $verify_code,];
                $send_res = Sms::sendSms($phone, 'register', $params);

                $res = 0;//默认发送失败
                if($send_res){
                    $data['relation'] = $phone;
                    $data['code_type'] = 1;//注册
                    $data['verify_code'] = $verify_code;
                    $data['expiration_time'] = date('Y-m-d H:i:s',strtotime("+5 minutes"));
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $data['ip'] = Yii::$app->request->userIP;

                    $res = Yii::$app->db->createCommand()
                        ->insert('sms_code',$data)
                        ->execute();
                }
                if($res){
                    return 1;   //发送成功
                }else{
                    return 2;   //发送失败
                }
            }
        }
        //验证短信验证码
        $vary_code = Myhelpers::RemoveXSS(Yii::$app->request->post('vary_code'));
        if($vary_code){
            $phone = Myhelpers::RemoveXSS(Yii::$app->request->post('phone'));
            $rows = (new \yii\db\Query())
                    ->select(['verify_code', 'is_used','expiration_time'])
                    ->from('sms_code')
                    ->where(['relation' => $phone,'code_type'=>1,'is_used'=>0])
                    ->orderBy('id desc')
                    ->one();
            if($rows){
                if(strtotime($rows['expiration_time'])<time()){
                    //验证码已经超时了
                    return 2;
                }else{
                    if($vary_code != $rows['verify_code']){
                        return 4;//failed
                    }else{
                        return 1;//success
                    }
                }
            }else{
                return 3;//请先获取验证码
            }
        }

        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    //return $this->goHome();
                    //修改页面标题
                    Yii::$app->view->params['page']['page_title'] = '注册 - ' . $this->w_config['website_name'];
                    return $this->render('registeryes');
                }
            }
        }
        //修改页面标题
        Yii::$app->view->params['page']['page_title'] = '注册 - ' . $this->w_config['website_name'];
        return $this->render('register', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
  

    //找回密码
    public function actionFindpassword()
    {
        //验证手机号发送短信
        $phone = Myhelpers::RemoveXSS(Yii::$app->request->post('phonecode'));

        if($phone){
            $phone_uni = User::find()->where(['phone'=>$phone])->count();
            if(!intval($phone_uni)){
                return 0;   //手机不存在
            }else{
                //生成验证码
                $verify_code = rand(1000,9999);

                //手机不在---调用接口发送短信---发送的时候保存到表里面
                //获取模板id
                $params = ['sms_code' => $verify_code,];
                $send_res = Sms::sendSms($phone, 'forget', $params);

                $res = 0;//默认发送失败
                if($send_res){
                    $data['relation'] = $phone;
                    $data['code_type'] = 4;//找回登陆密码
                    $data['verify_code'] = $verify_code;
                    $data['expiration_time'] = date('Y-m-d H:i:s',strtotime("+5 minutes"));
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $data['ip'] = Yii::$app->request->userIP;

                    $res = Yii::$app->db->createCommand()
                        ->insert('sms_code',$data)
                        ->execute();
                }
                if($res){
                    return 1;   //发送成功
                }else{
                    return 2;   //发送失败
                }
            }
        }
        //验证短信验证码
        $vary_code = Myhelpers::RemoveXSS(Yii::$app->request->post('vary_code'));
        if($vary_code){
            $phone = Myhelpers::RemoveXSS(Yii::$app->request->post('phone'));
            $rows = (new \yii\db\Query())
                    ->select(['verify_code', 'is_used','expiration_time'])
                    ->from('sms_code')
                    ->where(['relation' => $phone,'code_type'=>4,'is_used'=>0])
                    ->orderBy('id desc')
                    ->one();
            if($rows){
                if(strtotime($rows['expiration_time'])<time()){
                    //验证码已经超时了
                    return 2;
                }else{
                    if($vary_code != $rows['verify_code']){
                        return 4;//failed
                    }else{
                        return 1;//success
                    }
                }
            }else{
                return 3;//请先获取验证码
            }
        }

        //验证完成，操作数据库
        $reset_post = Yii::$app->request->post('FindPasswordForm');
        $reset_phone = Myhelpers::RemoveXSS($reset_post['phone']);
        $reset_pass = Myhelpers::RemoveXSS($reset_post['password']);

        if($reset_phone && $reset_pass){
            $pass_hash = Yii::$app->security->generatePasswordHash($reset_pass);

            $reset = Yii::$app->db->createCommand()
                ->update('user', ['password_hash' => $pass_hash], "phone =".$reset_phone)
                ->execute();
            if($reset){
                Yii::$app->view->params['page']['page_title'] = '找回密码 - ' . $this->w_config['website_name'];
                        return $this->render('findpass_suc');
            }
        }
        $model = new FindPasswordForm();
        //修改页面标题
        Yii::$app->view->params['page']['page_title'] = '找回密码 - ' . $this->w_config['website_name'];
        return $this->render('findpassword', [
            'model' => $model,
        ]);
    }

}